package com.beiding.my.common.query;

import com.beiding.my.common.Bo;
import com.beiding.my.common.QuoteExpressionRegistry;
import com.google.common.base.Joiner;

import java.util.ArrayList;
import java.util.List;

public class InnerConnectorHasBody extends InnerConnector {

    private String symbol;
    private Expression[] body;

    public InnerConnectorHasBody(Expression font) {
        super(font);
    }

    public void setBody(Expression[] body) {
        this.body = body;
    }

    public void setSymbol(String symbol) {
        this.symbol = " " + symbol + " ";
    }

    @Override
    protected String createExpressionLocal(QuoteExpressionRegistry registry, Class<? extends Bo> type, ParamHolderCreator paramHolderCreator, CreateResult createResult) {
        String and = font instanceof InnerConnectorNoBody ? "" : "and ";
        if (body.length > 0) {
            if (body.length == 1) {
                return body[0].createExpression(registry, type, paramHolderCreator, createResult);
            } else {
                List<String> cs = new ArrayList<>();
                for (Expression expression : body) {
                    cs.add("(" + expression.createExpression(registry, type, paramHolderCreator, createResult) + ")");
                }
                return and + "(" + Joiner.on(symbol).join(cs) + ")";
            }
        } else {
            return "";
        }
    }

    public InnerConnectorNoBody and() {
        InnerConnectorNoBody r = new InnerConnectorNoBody(this);
        r.setSymbol("and");
        return r;
    }

    public InnerConnectorNoBody or() {
        InnerConnectorNoBody r = new InnerConnectorNoBody(this);
        r.setSymbol("or");
        return r;
    }

}
